package com.achievement.service.impl;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.achievement.domain.dto.PaperEmbodyDTO;
import com.achievement.domain.entity.PaperEmbodyEntity;
import com.achievement.domain.entity.PaperIncludeEntity;
import com.achievement.domain.param.PaperEmbodyParam;
import com.achievement.domain.vo.PaperEmbodyVO;
import com.achievement.mapper.PaperEmbodyMapper;
import com.achievement.mappings.paper.PaperMapping;
import com.achievement.service.IAchievementFileService;
import com.achievement.service.IPaperEmbodyService;
import com.achievement.service.IPaperIncludeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.api.ApprovalApi;
import com.common.core.domain.AjaxResult;
import com.common.utils.DateUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.bean.BizProcessMessages;
import com.flowable.service.IFlowTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author CNKI
* @description 针对表【biz_paper_embody(科研成果-论文收录补录列表)】的数据库操作Service实现
* @createDate 2025-02-19 16:23:45
*/
@Service("biz_paper_embody")
public class PaperEmbodyServiceImpl extends ServiceImpl<PaperEmbodyMapper, PaperEmbodyEntity>
    implements IPaperEmbodyService {

    @Autowired
    private PaperMapping mapping;

    @Autowired
    private IAchievementFileService fileService;

    @Autowired
    private IPaperIncludeService paperIncludeService;

    @Autowired
    private ApprovalApi approvalApi;

    //流程引擎
    @Autowired
    private IFlowTaskService flowTaskService;

    private final static String module_name = "论文收录补录";

    /**
     * 查询论文收录补录列表
     *
     * @param param param
     */
    @Override
    public List<PaperEmbodyVO> selectByPage(PaperEmbodyParam param) {

        param.setEmbodyDateStart(DateUtils.dateStrHandle(param.getEmbodyDateStart(), param.getDateFormat(), "start"));
        param.setEmbodyDateEnd(DateUtils.dateStrHandle(param.getEmbodyDateEnd(), param.getDateFormat(), "end"));


        List<PaperEmbodyVO> paperVOList = this.baseMapper.getList(param);

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);

        paperVOList.stream().forEach(a -> {
            // 判断是否是审核人，并设置taskId
            String processInstanceId = a.getProcessInstanceId();
            if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                a.setTaskId(instanceTaskMap.get(processInstanceId));
                a.setIsAuditor(true);
            } else {
                a.setIsAuditor(false);
            }
        });

        return paperVOList;
    }

    /**
     * 论文收录补录查看详情
     *
     * @param id id
     */
    @Override
    public PaperEmbodyVO getInfoById(String id) {

        PaperEmbodyVO vo = this.baseMapper.getInfoById(id);

        //附件信息
        String fileIds = vo.getEmbodyFileId();
        if (StringUtils.hasText(fileIds)) {
            String[] fileIdArr = fileIds.split(",");
            List<Map<String,String>> fileInfo = fileService.getFileInfoByFileIds(fileIdArr);
            vo.setFileList(fileInfo);
        }

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
        // 判断是否是审核人，并设置taskId
        String processInstanceId = vo.getProcessInstanceId();
        if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
            vo.setTaskId(instanceTaskMap.get(processInstanceId));
            vo.setIsAuditor(true);
        } else {
            vo.setIsAuditor(false);
        }

        return vo;
    }

    /**
     * 新增论文收录补录
     *
     * @param dto dto
     */
    @Override
    public AjaxResult add(PaperEmbodyDTO dto) {
        if (ObjectUtil.isNull(dto)){
            return AjaxResult.error("数据为空");
        }

        String UUID = IdUtil.randomUUID().replace("-", "");

        dto.setId(UUID);

        PaperEmbodyEntity entity = mapping.PaperEmbodyDto2Entity(dto);


        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                entity.setProcessInstanceId("0");
                entity.setCheckstatus(String.valueOf(submitType));
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                break;
            case 1: // 提交
                entity.setCheckstatus(String.valueOf(submitType));
                if (!(this.save(entity))) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String processInstanceId = null;
                try {
                    //发起流程 业务状态由流程引擎更新
                    processInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS);
                }

                return StringUtils.isEmpty(processInstanceId)
                        ? AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success((Object)entity.getId());
            default: // 处理 -1（暂存）及其他情况
                entity.setCheckstatus(String.valueOf(submitType));
                break;
        }

        boolean r = this.save(entity);
        return r ? AjaxResult.success((Object)entity.getId()) : AjaxResult.error(BizProcessMessages.SAVE_FAIL);

    }

    /**
     * 左上方统计 通过，退回，待审核
     *
     * @param param param
     */
    @Override
    public List<HashMap<String, Integer>> listStatistics(PaperEmbodyParam param) {
        param.setEmbodyDateStart(DateUtils.dateStrHandle(param.getEmbodyDateStart(), param.getDateFormat(), "start"));
        param.setEmbodyDateEnd(DateUtils.dateStrHandle(param.getEmbodyDateEnd(), param.getDateFormat(), "end"));


        return  this.baseMapper.listStatistics(param);
    }

    /**
     * 删除论文收录补录
     *
     * @param ids ids
     */
    @Override
    public boolean batchRemove(List<String> ids) {
        return this.removeByIds(ids);
    }

    @Override
    public void updateBusinessStatus(String tableName, String businessId, String checkStatus, String sysUserId) {

        System.out.println("进入方法biz_paper_embody");
        System.out.println("tableName:"+tableName);

        if (StringUtils.isEmpty(tableName) || StringUtils.isEmpty(businessId) || StringUtils.isEmpty(checkStatus))
            return;
        PaperEmbodyEntity entity = new PaperEmbodyEntity();
        entity.setId(businessId);
        entity.setCheckstatus(checkStatus);
        if ("2".equals(checkStatus)) {
            entity.setCheckdate(DateUtils.getTime());
            entity.setChecker(SecurityUtils.getNickName());

            PaperEmbodyEntity paperEmbodyEntity = this.baseMapper.selectById(businessId);

            //同步到论文收录表中
            PaperIncludeEntity paperIncludeEntity = mapping.entity2PaperInclude(paperEmbodyEntity);
            paperIncludeService.save(paperIncludeEntity);
        }

        this.updateById(entity);
    }
}




